package com.lwj.liwanjia.view.activity.work.shang_jia.ding_dan;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.TuiKuanKuaiDiAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.TuikuanBean;
import com.lwj.liwanjia.bean.WuLiuBean01;
import com.lwj.liwanjia.bean.WuLiuBean02;
import com.lwj.liwanjia.config.URLConstant;
import com.lwj.liwanjia.impl.TuikuanView;
import com.lwj.liwanjia.presenter.TuikuanPresenter;
import com.lwj.liwanjia.utils.MyRecyclerView;
import com.lwj.liwanjia.utils.SpfUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 001 on 2017/11/1.
 */

public class WuLiuActivity extends BaseActivity implements View.OnClickListener, TuikuanView {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 0:
                    Toast.makeText(WuLiuActivity.this, "数据有误", Toast.LENGTH_LONG).show();
                    break;

                case 1:

                    if (!TextUtils.isEmpty(name01)) {
                        tv_01.setText(name01);
                    }

                    if (!TextUtils.isEmpty(name02)) {
                        tv_02.setText(name02);
                    }

                    if (!TextUtils.isEmpty(name03)) {
                        tv_03.setText(name03);
                    }

                    if (!TextUtils.isEmpty(name04)) {
                        tv_04.setText(name04);
                    } else {
                        ll04.setVisibility(View.GONE);
                    }

                    switch (name02) {

                        case "顺丰快递":
                            kuaiDiType = "sf";
                            break;

                        case "圆通快递":
                            kuaiDiType = "yt";
                            break;

                        case "申通快递":
                            kuaiDiType = "sto";
                            break;

                        case "韵达快递":
                            kuaiDiType = "yd";
                            break;

                        case "天天快递":
                            kuaiDiType = "tt";
                            break;

                        case "中通快递":
                            kuaiDiType = "zto";
                            break;

                        case "汇通快递":
                            kuaiDiType = "ht";
                            break;

                        case "德邦快递":
                            kuaiDiType = "db";
                            break;

                    }
                    if (!TextUtils.isEmpty(kuaiDiType) && !TextUtils.isEmpty(name03)) {
                        //物流查询
                        initOkHttp02(kuaiDiType, name03);
                    }
                    break;
                case 2:

                    if (homeList != null && homeList.size() >= 0) {

                        //倒序
                        Collections.reverse(homeList);

                        //必须延迟一会
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                LinearLayoutManager manager = new LinearLayoutManager(WuLiuActivity.this);
                                mRecyclerView.setLayoutManager(manager);
                                homeAdapter = new TuiKuanKuaiDiAdapter(WuLiuActivity.this, homeList);
                                mRecyclerView.setAdapter(homeAdapter);
                            }
                        }, 10);
                    }

                    break;
            }
        }
    };

    private TextView tv_back;
    private TextView tv_title;
    private TuiKuanKuaiDiAdapter homeAdapter;
    private List<WuLiuBean01.ResultBean.ListBean> homeList;
    private MyRecyclerView mRecyclerView;
    private TextView tv_01;
    private TextView tv_02;
    private TextView tv_03;
    private TextView tv_04;
    private String dingDanHao;//订单号
    private String name01;
    private String name02;
    private String name03;
    private String name04;
    private LinearLayout ll04;
    private String kuaiDiType = "sf";
    private String dingDanState;
    private TextView tvTuikuan;
    private TuikuanPresenter presenter;
    private String token;

    @Override
    protected void initView() {

        tv_back = (TextView) findViewById(R.id.tv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        mRecyclerView = (MyRecyclerView) findViewById(R.id.recyclerView);

        tv_01 = (TextView) findViewById(R.id.tv_01);
        tv_02 = (TextView) findViewById(R.id.tv_02);
        tv_03 = (TextView) findViewById(R.id.tv_03);
        tv_04 = (TextView) findViewById(R.id.tv_04);
        ll04 = (LinearLayout) findViewById(R.id.ll_04);
        tvTuikuan = (TextView) findViewById(R.id.tv_tuikuan);

        tv_back.setVisibility(View.VISIBLE);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("物流");
        presenter = new TuikuanPresenter(this);
        token = SpfUtils.getSpfUtils(this).getToken();

        tv_back.setOnClickListener(this);
        tvTuikuan.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        dingDanHao = intent.getStringExtra("dingDanHao");
        dingDanState = intent.getStringExtra("dingDanState");
        if (dingDanState != null) {
            if (dingDanState.equals("换货中") || dingDanState.equals("退款退货中"))
                tvTuikuan.setVisibility(View.VISIBLE);
        }
        //请求网络 获取数据
        initOkHttp01();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wu_liu;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.tv_left:
                finish();
                break;
            case R.id.tv_tuikuan:
                presenter.sureTuikuan(dingDanHao, token);
                break;
        }
    }

    //请求网络 获取数据
    private void initOkHttp01() {

        String url = URLConstant.BASE_URL + "order/orderLogistics";
        String token = SpfUtils.getSpfUtils(this).getToken();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("tradeId", dingDanHao)
                .add("token", token)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = null;

                try {
                    result = response.body().string();
                    parseInitOkHttp01(result);
                } catch (Exception e) {

                }

            }
        });
    }

    //解析数据
    private void parseInitOkHttp01(String reuslt) {

        Gson gson = new Gson();
        WuLiuBean02 bean = gson.fromJson(reuslt, WuLiuBean02.class);

        if (bean != null) {

            switch (bean.getState()) {

                case 0:
                    mHandler.sendEmptyMessage(0);
                    break;

                case 1:

                    name01 = bean.getData().getTradeId();
                    name02 = bean.getData().getCompany();
                    name03 = bean.getData().getLogisticsId();
                    name04 = bean.getData().getPayInfo();

                    mHandler.sendEmptyMessage(1);

                    break;
            }
        }
    }

    //物流查询
    private void initOkHttp02(String tv_02, String tv_03) {

        String url = "http://v.juhe.cn/exp/index?key=47906c43bcfacd1abe0483624323f61e&com=" + tv_02 + "&no=" + tv_03;

        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(url);

        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = response.body().string();
                if (result != null) {
                    parseOkHttp02(result);
                }
            }
        });

    }

    //解析物流查询
    private void parseOkHttp02(String result) {

        Gson gson = new Gson();
        WuLiuBean01 bean = gson.fromJson(result, WuLiuBean01.class);

        if (bean != null && bean.getResultcode().equals("200")) {

            homeList = new ArrayList<>();

            for (int i = 0; i < bean.getResult().getList().size(); i++) {

                WuLiuBean01.ResultBean.ListBean listBean = bean.getResult().getList().get(i);
                homeList.add(listBean);
            }

            mHandler.sendEmptyMessage(2);
        } else {
            mHandler.sendEmptyMessage(0);
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void sureTuikuan(TuikuanBean tuikuanBean) {
        if (tuikuanBean.getState() == 0) {
            Toast.makeText(this, "余额不足", Toast.LENGTH_SHORT).show();
        } else if (tuikuanBean.getState() == 1) {
            if (tuikuanBean.getData().getState().equals("退款成功")) {
                Toast.makeText(this, "退款成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter = null;
        }
        super.onDestroy();
    }
}
